package com.example.yiwei.crm.view.activity.coordinationActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.data.GetAppointment;
import com.example.yiwei.crm.entity.ApointmentEntity;
import com.example.yiwei.crm.json.ApointmentJson;
import com.example.yiwei.crm.util.NetWorkUtils;
import com.example.yiwei.crm.util.SC;
import com.example.yiwei.crm.view.Class.listviewClass.AutoListView;
import com.example.yiwei.crm.view.Class.listviewClass.ManyiduAdapter;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionMenu;
import com.oguzdev.circularfloatingactionmenu.library.SubActionButton;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;


public class ManYiDuActivity extends AppCompatActivity implements AutoListView.OnRefreshListener,AutoListView.OnLoadListener{
    ImageView fabIconStar;
    FloatingActionMenu leftCenterMenu;
    //    FloatingActionMenu leftCenterMenu1;
    FloatingActionButton leftCenterButton;
    FloatingActionButton leftCenterButton1;
    ImageView lcIcon1 ;
    ImageView lcIcon2 ;
    ImageView lcIcon3 ;
    private AutoListView listView;
    private ManyiduAdapter adapter;
    AlertDialog.Builder builder;
    ImageView img_back,img_search;
    int customer_id;
    int a=1;
    int page = 1;
    private List<ApointmentEntity> list;
    private List<ApointmentEntity> alist;
    int appoint_id;
    String manyidu;
    String theme[]={"非常满意","满意","一般","不满意"};
    private SharedPreferences sp;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            List<ApointmentEntity> result = (List<ApointmentEntity>) msg.obj;
            switch (msg.what) {
                case AutoListView.REFRESH:
                    listView.onRefreshComplete();
                    if (list!=null){
                        list.clear();
                    }
                    if (list!=null){
                        list.addAll(result);
                    }else {
                        list = result;
                    }
                    if (a==1){
                        adapter = new ManyiduAdapter(ManYiDuActivity.this,list);
                        listView.setAdapter(adapter);
                        a++;
                    }
                    break;
                case AutoListView.LOAD:
                    if (result!=null){
                        listView.onLoadComplete();
                        list.addAll(result);
                    }else {
                        listView.onLoadComplete();
                    }
                    break;
            }
            if (result!=null) {
//                listView.setResultSize(result.size());
            }else{
//                listView.setResultSize(0);
            }
            adapter.notifyDataSetChanged();
        }


    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_man_yi_du);
        listView= (AutoListView) findViewById(R.id.simple_health_education_listview);
        listView.setDivider(new ColorDrawable(Color.rgb(216, 216, 216)));
        img_back= (ImageView) findViewById(R.id.manyiu_img_back);
        img_search= (ImageView) findViewById(R.id.manyidu_img_search);
        sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        listView.setDividerHeight(1);
        listView.setOnRefreshListener(this);
        listView.setOnLoadListener(this);
        addXuanFu1();
        //添加满意度
        lcIcon1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (list!=null&&list.size()!=0) {
                    if (ManyiduAdapter.getIDs().size() == 1) {
                        for (int i = 0; i < list.size(); i++) {
                            if (ManyiduAdapter.getIDs().get(0) == list.get(i).getAppoint_id()) {
                                if (0 == list.get(i).getIs_add()) {
                                    appoint_id = ManyiduAdapter.getIDs().get(0);
                                    customer_id = ManyiduAdapter.getCustomerIDs().get(0);
                                    Intent intent = new Intent(ManYiDuActivity.this, AddMYDActivity.class);
                                    intent.putExtra("KYA01", appoint_id);
                                    intent.putExtra("KAA01", customer_id);
                                    startActivity(intent);
                                } else {
                                    Toast.makeText(ManYiDuActivity.this, "此条记录已添加过满意度", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }


                    } else {
                        Toast.makeText(ManYiDuActivity.this, "请选择一个预约记录", Toast.LENGTH_SHORT).show();
                    }
                }
            }

        });
        //查看满意度
        lcIcon2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (list != null && list.size() != 0) {
                    if (ManyiduAdapter.getIDs().size() == 1) {
                        appoint_id = ManyiduAdapter.getIDs().get(0);
                        customer_id = ManyiduAdapter.getCustomerIDs().get(0);
                        Intent intent = new Intent(ManYiDuActivity.this, CoorDetileManYiDuActivity.class);
                        intent.putExtra("KYA01", appoint_id);
                        intent.putExtra("KAA01", customer_id);
                        startActivity(intent);
                    } else {
                        Toast.makeText(ManYiDuActivity.this, "请选择一个预约记录", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        //修改满意度
        lcIcon3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (list != null && list.size() != 0) {
                    if (ManyiduAdapter.getIDs().size() == 1) {
                        for (int i = 0; i < list.size(); i++) {
                            if (ManyiduAdapter.getIDs().get(0) == list.get(i).getAppoint_id()) {
                                if (1 == list.get(i).getIs_add()) {
                                    appoint_id = ManyiduAdapter.getIDs().get(0);
                                    customer_id = ManyiduAdapter.getCustomerIDs().get(0);
                                    Intent intent = new Intent(ManYiDuActivity.this, AddMYDActivity.class);
                                    intent.putExtra("KYA01", appoint_id);
                                    intent.putExtra("KAA01", customer_id);
                                    intent.putExtra("tag", "update");
                                    startActivity(intent);
                                } else {
                                    Toast.makeText(ManYiDuActivity.this, "此条记录还没有添加满意度", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }

                    } else {
                        Toast.makeText(ManYiDuActivity.this, "请选择一个预约记录", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        GetAppointment.create();
        GetAppointment.apoint=null;
        new Thread(new Runnable() {
            @Override
            public void run() {
                SC sc = new SC();
                JSONObject object = sc.storage(sp);
                try {
                    object.put("depts",sp.getString("DEPTS",null));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json = object.toString();
                String result = NetWorkUtils.getCount(baseClass.find_AllYY_URL+1,json);
                list = ApointmentJson.getApointment(result);
                if (list!=null){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(list!=null){
                                adapter = new ManyiduAdapter(ManYiDuActivity.this,list);
                                listView.setAdapter(adapter);
                                a++;
                                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                        GetAppointment.create();
                                        GetAppointment.apoint = list.get(position-1);
                                        Intent intent = new Intent(ManYiDuActivity.this,DetailedManyiduActivity.class);
                                        startActivity(intent);
                                    }
                                });
                            }
                        }
                    });
                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(ManYiDuActivity.this, "没有记录", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

            }
        }).start();
        img_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(ManYiDuActivity.this,SeacherMYDActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onLoad() {
        loadData(AutoListView.LOAD);
    }

    @Override
    public void onRefresh() {
        loadData(AutoListView.REFRESH);
    }

    public void onClick(View view) {
        switch (view.getId()){

        }
    }

    class LoadTask extends AsyncTask<Void,Integer,Integer> {
        Message msg = handler.obtainMessage();
        @Override
        protected Integer doInBackground(Void... voids) {
            int what = 1;
            msg.what = what;
            page=page+1;
            SC sc = new SC();
            JSONObject object = sc.storage(sp);
            try {
                object.put("depts",sp.getString("DEPTS",null));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String json = object.toString();
            String result = NetWorkUtils.getCount(baseClass.find_AllYY_URL+page,json);
            alist = ApointmentJson.getApointment(result);
            return null;
        }
        @Override
        protected void onPostExecute(Integer integer) {
            if (alist!=null){
                msg.obj = alist;
                handler.sendMessage(msg);
            }else {
                msg.obj = alist;
                handler.sendMessage(msg);
                Toast.makeText(ManYiDuActivity.this, "无更多信息", Toast.LENGTH_SHORT).show();
            }
            super.onPostExecute(integer);
        }
    }
    class UpdateTextTask extends AsyncTask<Void,Integer,Integer> {
        Message msg = handler.obtainMessage();
        @Override
        protected Integer doInBackground(Void... voids) {
            int what = 0;
            msg.what = what;
            page =1;
            SC sc = new SC();
            JSONObject object = sc.storage(sp);
            try {
                object.put("depts",sp.getString("DEPTS",null));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String json = object.toString();
            String result = NetWorkUtils.getCount(baseClass.find_AllYY_URL+1,json);
            alist = ApointmentJson.getApointment(result);
            return null;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            if (alist!=null){
                if(listView.getVisibility()==View.GONE){
                    listView.setVisibility(View.VISIBLE);
                }
                msg.obj = alist;
                handler.sendMessage(msg);
            }else {
                listView.setVisibility(View.GONE);
            }
            super.onPostExecute(integer);
        }
    }
    private void loadData(int refresh) {
        if (refresh== AutoListView.REFRESH){
            UpdateTextTask updateTextTask = new UpdateTextTask();
            updateTextTask.execute();
        }else if(refresh== AutoListView.LOAD){
            LoadTask loadTask = new LoadTask();
            loadTask.execute();
        }
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        if (GetAppointment.apoint1!=null){
            list.clear();
            list.addAll(GetAppointment.apoint1);
            adapter.notifyDataSetChanged();
            GetAppointment.apoint1=null;
        }else {
            onRefresh();
        }

    }
    public void  addXuanFu1(){
        /**
         * 一个FloatingActionButton有一个FloatingActionMenu，FloatingActionMenu添加动画弹出的子菜单。
         * FloatingActionButton的按钮点击事件将触发、弹出FloatingActionMenu中包含的子菜单。
         * FloatingActionMenu使用attachTo方法附着在一个FloatingActionButton上。
         * FloatingActionMenu在attachTo到一个FloatingActionButton后，两者之间发生关联。
         * FloatingActionMenu在添加子菜单时候，首先需要一个SubActionButton.Builder，该SubActionButton.
         * Builder通过setContentView(ImageView
         * image).build()把一个ImageView创建生产一个SubActionButton ,
         * 然后通过FloatingActionMenu.Builder的add方法把前面生成的SubActionButton添加进去。
         *
         *
         * 按钮的旋转动画在onMenuOpened和onMenuClosed中做。
         *
         */
        WindowManager wm = (WindowManager) getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);

        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        //按钮的大小
        int redActionButtonSize = getResources().getDimensionPixelSize(R.dimen.red_action_button_size1);
        //距离下边的长度
        int redActionButtonMargin = 7;
        //距离右边的长度
        int redActionButtonMarginRight = width/2-getResources().getDimensionPixelSize(R.dimen.red_action_button_content_size)/2;
        //按钮中内容的大小
        int redActionButtonContentSize = getResources().getDimensionPixelSize(R.dimen.red_action_button_content_size);
        int redActionButtonContentMargin = getResources()
                .getDimensionPixelSize(R.dimen.red_action_button_content_margin);
        //弹出圆弧的半径
        int redActionMenuRadius = getResources().getDimensionPixelSize(R.dimen.red_action_menu_radius2);
        int blueSubActionButtonSize = getResources().getDimensionPixelSize(R.dimen.blue_sub_action_button_size);
        int blueSubActionButtonContentMargin = getResources()
                .getDimensionPixelSize(R.dimen.blue_sub_action_button_content_margin);

        fabIconStar = new ImageView(this);
//        if (leftCenterMenu.isOpen()){
//            fabIconStar.setImageDrawable(getResources().getDrawable(R.drawable.jiahao2));
//        }else{
//            //按钮中的图片
        fabIconStar.setImageDrawable(getResources().getDrawable(R.drawable.plus5));
//        }


        FloatingActionButton.LayoutParams starParams = new FloatingActionButton.LayoutParams(redActionButtonSize,
                redActionButtonSize);
        starParams.setMargins(redActionButtonMargin, redActionButtonMargin, redActionButtonMarginRight,
                redActionButtonMargin);
        fabIconStar.setLayoutParams(starParams);

        FloatingActionButton.LayoutParams fabIconStarParams = new FloatingActionButton.LayoutParams(
                redActionButtonContentSize, redActionButtonContentSize);
        fabIconStarParams.setMargins(redActionButtonContentMargin, redActionButtonContentMargin,
                redActionButtonContentMargin, redActionButtonContentMargin);
//        if (leftCenterMenu.isOpen()){
//            leftCenterButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.yuan2));
//        }else{
//            leftCenterButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.yuan1));
//        }
        leftCenterButton = new FloatingActionButton.Builder(this)
                .setContentView(fabIconStar, fabIconStarParams)
                .setBackgroundDrawable(R.drawable.button_action_red_selector)// 设置变化时的背景色
                .setPosition(FloatingActionButton.POSITION_BOTTOM_RIGHT)// 靠近右边和下边
                .setLayoutParams(starParams).build();

        // Set up customized SubActionButtons for the right center menu
        SubActionButton.Builder lCSubBuilder = new SubActionButton.Builder(this);
        lCSubBuilder.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_action_blue_selector));

        FrameLayout.LayoutParams blueContentParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT);
        blueContentParams.setMargins(blueSubActionButtonContentMargin, blueSubActionButtonContentMargin,
                blueSubActionButtonContentMargin, blueSubActionButtonContentMargin);
        lCSubBuilder.setLayoutParams(blueContentParams);
        // Set custom layout params
        FrameLayout.LayoutParams blueParams = new FrameLayout.LayoutParams(blueSubActionButtonSize,
                blueSubActionButtonSize);
        lCSubBuilder.setLayoutParams(blueParams);

//        ImageView lcIcon1 = new ImageView(this);
//        ImageView lcIcon2 = new ImageView(this);
//        ImageView lcIcon3 = new ImageView(this);
//
//        lcIcon1.setImageDrawable(getResources().getDrawable(R.drawable.u116));
//        lcIcon2.setImageDrawable(getResources().getDrawable(R.drawable.u117));
//        lcIcon3.setImageDrawable(getResources().getDrawable(R.drawable.u118));
        //添加按钮
        lcIcon1 = new ImageView(this);
        lcIcon2 = new ImageView(this);
        lcIcon3 = new ImageView(this);
//         lcIcon4 = new TextView(this);
        lcIcon1.setImageDrawable(getResources().getDrawable(R.drawable.tj1));
        lcIcon2.setImageDrawable(getResources().getDrawable(R.drawable.ck1));
        lcIcon3.setImageDrawable(getResources().getDrawable(R.drawable.xk));
//        lcIcon4.setText("选择部门");
        // Build another menu with custom options
        leftCenterMenu = new FloatingActionMenu.Builder(this)
                .addSubActionView(lCSubBuilder.setContentView(lcIcon1, blueContentParams).build())
                .addSubActionView(lCSubBuilder.setContentView(lcIcon2, blueContentParams).build())
                .addSubActionView(lCSubBuilder.setContentView(lcIcon3, blueContentParams).build())
                .setRadius(redActionMenuRadius).setStartAngle(240).setEndAngle(300).attachTo(leftCenterButton).build();



    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            FloatingActionMenu v = leftCenterMenu;
            if (isShouldHideKeyboard(v, ev)) {
//                Toast.makeText(this, aBoolean+"", Toast.LENGTH_SHORT).show();
                if (leftCenterMenu.isOpen()){
                    leftCenterMenu.close(true);
//                    fabIconStar.setImageDrawable(getResources().getDrawable(R.drawable.jiahao1));
//                    leftCenterButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.yuan1));
                }else{


                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据控件所在坐标和用户点击的坐标相对比，来判断是否隐藏，因为当用户点击控件时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(FloatingActionMenu v, MotionEvent event) {
        if (v != null ) {
            int[] l = {100, 100};
            int left = l[0],
                    top = l[1],
                    bottom = top ,
                    right = left ;
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击控件的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是控件则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }
}
